// 数据库操作
const fsPromises = require('fs').promises
const path = require('path')
// 数据库存储路径
const { dbDir } = require('../config/config.default')

async function getFilePath (tableName) {
  const filepath = path.join(dbDir, tableName + '.json')

  try {
    await fsPromises.access(filepath)
    return path.join(dbDir, tableName + '.json')
  } catch (error) {
    return Promise.reject(new Error(`${tableName} 表不存在`))
  }
}

const getTable = async tableName => {
  const filepath = await getFilePath(tableName)

  try {
    const dataStr = await fsPromises.readFile(filepath, 'utf8')
    return JSON.parse(dataStr)
  } catch (error) {
    return Promise.reject(new Error(`${tableName} 表解析数据失败`))
  }
}

const setTable = async (tableName, data) => {
  const filepath = await getFilePath(tableName)

  await fsPromises.writeFile(filepath, JSON.stringify(data), 'utf8')
}

// 获取未删除的数据
const getUnDelData = async (tableName) => {
  const list = await getTable(tableName)
  return list.filter(v => !v.isDel)
}

module.exports = {
  getTable,
  setTable,
  getUnDelData
}
